#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

typedef struct doublelist
{
	//数据域
	int data;
	//指针域 
	struct doublelist *next; //指向后一个节点 
	struct doublelist *prev; //指向前一个节点 
}dlist;

//封装函数实现双向链表的初始化--》初始化头结点(链表的第一个节点)
struct doublelist *list_init()
{
	//定义指针申请堆空间
	struct doublelist *head=malloc(sizeof(struct doublelist));
	head->next=NULL;
	head->prev=NULL;
	return head;
}

//尾插
int list_insert_tail(int newdata,struct doublelist *head)
{
	struct doublelist *p=head;
	//找到尾部--》跟单链表一模一样
	while(p->next!=NULL)
		p=p->next;
	
	//准备新的节点
	struct doublelist *newnode=malloc(sizeof(struct doublelist));
	newnode->data=newdata;
	newnode->prev=NULL;
	newnode->next=NULL;
	
	//尾插这个新节点
	p->next=newnode;
	newnode->prev=p;
	return 0;
}

//中间插入，插入到某个节点的前面
int list_insert_mid1(int newdata,int olddata,struct doublelist *head)
{
	//找到olddata
	struct doublelist *p=head;
	while(p->next!=NULL)
	{
		p=p->next;
		if(p->data==olddata)
			break;
	}
	
	//准备新的节点
	struct doublelist *newnode=malloc(sizeof(struct doublelist));
	newnode->data=newdata;
	newnode->prev=NULL;
	newnode->next=NULL;
	
	//把新的节点插入到olddata对应节点的前面
	newnode->prev=p->prev;
	p->prev->next=newnode;
	p->prev=newnode;
	newnode->next=p;
	return 0;
}

//打印
int list_show(struct doublelist *head)
{
	struct doublelist *p=head;
	while(p->next!=NULL)
	{
		p=p->next;
		printf("当前链表中存放的是: %d\n",p->data);
	}
	return 0;
}

int list_delete(struct doublelist *head){
    struct doublelist *p = head;
    while(p != NULL){
        struct doublelist *temp = p;
        p = p->next;
        free(temp);
    }
    return 0;
}

int main()
{
	//初始化双向链表
	struct doublelist *myhead=list_init();
	
	//尾插数据
	list_insert_tail(45,myhead);
	list_insert_tail(75,myhead);
	list_insert_tail(14,myhead);
	list_insert_tail(685,myhead);
	list_insert_tail(47,myhead);
	list_insert_tail(4752,myhead);
	
	//打印
	printf("============尾插之后============\n");
	list_show(myhead);
	
	//中间插入，插入到某个节点的前面
	list_insert_mid1(111,4752,myhead); //把111插入到4752的前面
	printf("============中间插入之后============\n");
	list_show(myhead);

    list_delete(myhead);
    printf("============删除之后============\n");
    list_show(myhead);
	return 0;

}

